import tkinter as tk
from tkinter import ttk, messagebox
from tkinter import PhotoImage
from ledger import GiftLedger
from ui.dialogs import add_record_dialog, edit_record_dialog
import threading
import logging

class GiftManagerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("人情礼簿管理系统")
        self.root.geometry("800x600")
        self.root.configure(bg="#f0f0f0")

        self.send_ledger = GiftLedger("send")
        self.receive_ledger = GiftLedger("receive")
        self.current_ledger = None

        self.create_widgets()
        self.show_ledger_selector()

    def create_widgets(self):
        self.main_frame = ttk.Frame(self.root, padding="10", style="TFrame")
        self.main_frame.grid(row=0, column=0, sticky="nsew")
        self.root.grid_rowconfigure(0, weight=1)
        self.root.grid_columnconfigure(0, weight=1)

        self.toolbar = ttk.Frame(self.main_frame, style="Toolbar.TFrame")
        self.toolbar.grid(row=0, column=0, sticky="ew", pady=5)

        self.tree = ttk.Treeview(self.main_frame, columns=('ID', '姓名', '金额', '日期', '关系', '场合', '备注'),
                                 show='headings', style="Treeview")
        self.tree.grid(row=1, column=0, sticky="nsew")
        self.main_frame.grid_rowconfigure(1, weight=1)
        self.main_frame.grid_columnconfigure(0, weight=1)

        columns = {
            'ID': 50, '姓名': 100, '金额': 80,
            '日期': 120, '关系': 100, '场合': 120, '备注': 200
        }
        for col, width in columns.items():
            self.tree.heading(col, text=col)
            self.tree.column(col, width=width, anchor=tk.W)

        scrollbar = ttk.Scrollbar(self.main_frame, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscroll=scrollbar.set)
        scrollbar.grid(row=1, column=1, sticky="ns")

        self.context_menu = tk.Menu(self.root, tearoff=0)
        self.context_menu.add_command(label="编辑", command=self.edit_selected)
        self.context_menu.add_command(label="删除", command=self.delete_selected)

        self.tree.bind("<Button-3>", self.show_context_menu)

        style = ttk.Style()
        style.configure("TFrame", background="#f0f0f0")
        style.configure("Toolbar.TFrame", background="#e0e0e0")
        style.configure("Treeview", background="#ffffff", foreground="black", fieldbackground="#ffffff")
        style.map("Treeview", background=[('selected', '#c0c0c0')])
        style.configure("Treeview.Heading", background="#e0e0e0", foreground="black")
        style.configure("TButton", font=("Arial", 10))

    def show_ledger_selector(self):
        selector = tk.Toplevel(self.root)
        selector.title("选择账本")
        selector.geometry("300x150")
        selector.configure(bg="#f0f0f0")

        ttk.Label(selector, text="请选择要管理的账本类型", font=('Arial', 12), background="#f0f0f0").pack(pady=10)

        try:
            add_icon = PhotoImage(file="icons/add.png").subsample(20, 20)
            ttk.Button(selector, text="随礼账本", image=add_icon, compound=tk.LEFT,
                       command=lambda: self.set_ledger("send", selector)).pack(pady=5)
            ttk.Button(selector, text="收礼账本", image=add_icon, compound=tk.LEFT,
                       command=lambda: self.set_ledger("receive", selector)).pack(pady=5)
        except Exception as e:
            logging.error(f"Failed to load icons: {e}")

    def set_ledger(self, ledger_type, selector):
        selector.destroy()
        self.current_ledger = self.send_ledger if ledger_type == "send" else self.receive_ledger
        self.create_toolbar()
        self.refresh_table()

    def create_toolbar(self):
        for widget in self.toolbar.winfo_children():
            widget.destroy()

        try:
            add_icon = PhotoImage(file="icons/add.png").subsample(20, 20)
            refresh_icon = PhotoImage(file="icons/refresh.png").subsample(20, 20)
            stats_icon = PhotoImage(file="icons/stats.png").subsample(20, 20)

            ttk.Button(self.toolbar, text="添加记录", image=add_icon, compound=tk.LEFT, command=self.add_record).pack(side=tk.LEFT, padx=5)
            ttk.Button(self.toolbar, text="刷新数据", image=refresh_icon, compound=tk.LEFT, command=self.refresh_table).pack(side=tk.LEFT, padx=5)
            ttk.Button(self.toolbar, text="统计图表", image=stats_icon, compound=tk.LEFT, command=self.show_stats).pack(side=tk.LEFT, padx=5)
        except Exception as e:
            logging.error(f"Failed to load icons: {e}")

    def refresh_table(self):
        def load_data():
            for item in self.tree.get_children():
                self.tree.delete(item)

            for record in self.current_ledger.records:
                self.tree.insert('', tk.END, values=(
                    record['id'],
                    record['name'],
                    f"￥{record['amount']}",
                    record['date'],
                    record.get('relationship', ''),
                    record.get('occasion', ''),
                    record.get('notes', '')
                ))
            logging.info("Refreshed the table")

        thread = threading.Thread(target=load_data)
        thread.start()

    def add_record(self):
        add_record_dialog(self.root, self.current_ledger, self.refresh_table)

    def edit_selected(self):
        selected = self.tree.selection()
        if not selected:
            return

        record_id = int(self.tree.item(selected[0], 'values')[0])
        edit_record_dialog(self.root, self.current_ledger, self.refresh_table, record_id)

    def delete_selected(self):
        selected = self.tree.selection()
        if not selected:
            return

        record_id = int(self.tree.item(selected[0], 'values')[0])
        if messagebox.askyesno("确认删除", "确定要删除这条记录吗？"):
            self.current_ledger.delete_record(record_id)
            self.refresh_table()
            logging.info(f"Confirmed to delete record with ID {record_id}")

    def show_context_menu(self, event):
        item = self.tree.identify_row(event.y)
        if item:
            self.tree.selection_set(item)
            self.context_menu.post(event.x_root, event.y_root)

    def show_stats(self):
        stats_window = tk.Toplevel(self.root)
        stats_window.title("统计信息")
        stats_window.configure(bg="#f0f0f0")

        total_send = sum(r['amount'] for r in self.send_ledger.records)
        total_receive = sum(r['amount'] for r in self.receive_ledger.records)

        ttk.Label(stats_window, text="随礼统计", font=('Arial', 12, 'bold'), background="#f0f0f0").pack(pady=5)
        ttk.Label(stats_window, text=f"总记录数：{len(self.send_ledger.records)}", background="#f0f0f0").pack()
        ttk.Label(stats_window, text=f"总金额：￥{total_send:.2f}", background="#f0f0f0").pack()

        ttk.Label(stats_window, text="收礼统计", font=('Arial', 12, 'bold'), background="#f0f0f0").pack(pady=5)
        ttk.Label(stats_window, text=f"总记录数：{len(self.receive_ledger.records)}", background="#f0f0f0").pack()
        ttk.Label(stats_window, text=f"总金额：￥{total_receive:.2f}", background="#f0f0f0").pack()